<?php
declare (strict_types = 1);

namespace app\controller\api;

use app\BaseController;
use app\model\Admin as AdminModel;
use think\facade\Session;
use app\service\AuthService;
use app\service\LogService;
use app\service\MenuService;
use app\service\RoleService;

class Login extends BaseController
{
    protected $logService;
    protected $authService;
    protected $menuService;
    protected $roleService;

    protected function initialize()
    {
        parent::initialize();
        $this->logService = new LogService();
        $this->authService = new AuthService();
        $this->menuService = new MenuService();
        $this->roleService = new RoleService();
    }

    /**
     * 登录
     */
    public function login()
    {
        $username = input('post.username');
        $password = input('post.password');
        
        if (empty($username) || empty($password)) {
            $this->error('用户名和密码不能为空');
        }
        
        $admin = AdminModel::where('username', $username)->find();
        if (!$admin) {
            $this->error('用户名或密码错误');
        }
        
        if ($admin['status'] != 1) {
            $this->error('账号已被禁用');
        }
        
        if (!password_verify($password, $admin['password'])) {
            $this->error('用户名或密码错误');
        }
        
        // 更新登录信息
        $admin->save([
            'last_login_time' => time(),
            'last_login_ip' => request()->ip()
        ]);
        
        // 记录登录日志
        $this->logService->addLog($admin['id'], 'login', '登录成功');
        
        // 设置session
        session('admin_id', $admin['id']);
        session('admin_name', $admin['username']);
        
        $this->success('登录成功', [
            'id' => $admin['id'],
            'username' => $admin['username'],
            'nickname' => $admin['nickname']
        ]);
    }
    
    /**
     * 退出登录
     */
    public function logout()
    {
        $adminId = session('admin_id');
        if ($adminId) {
            // 记录退出日志
            $this->logService->addLog($adminId, 'logout', '退出登录');
        }
        
        // 清除session
        session('admin_id', null);
        session('admin_name', null);
        
        $this->success('退出成功');
    }

    /**
     * 获取管理员信息
     */
    public function getInfo()
    {
        $adminId = session('admin_id');
        if (!$adminId) {
            $this->error('请先登录', null, 401);
        }
        
        $admin = AdminModel::find($adminId);
        if (!$admin) {
            $this->error('管理员不存在');
        }
        
        // 获取权限列表
        $authList = $this->authService->getAuthList($adminId);
        
        $this->success('获取成功', [
            'id' => $admin['id'],
            'username' => $admin['username'],
            'nickname' => $admin['nickname'],
            'avatar' => $admin['avatar'],
            'auth_list' => $authList
        ]);
    }

    /**
     * 修改密码
     */
    public function updatePassword()
    {
        $adminId = session('admin_id');
        if (!$adminId) {
            $this->error('请先登录', null, 401);
        }
        
        $oldPassword = input('post.old_password');
        $newPassword = input('post.new_password');
        $confirmPassword = input('post.confirm_password');
        
        if (empty($oldPassword) || empty($newPassword) || empty($confirmPassword)) {
            $this->error('请填写完整信息');
        }
        
        if ($newPassword !== $confirmPassword) {
            $this->error('两次输入的密码不一致');
        }
        
        $admin = AdminModel::find($adminId);
        if (!$admin) {
            $this->error('管理员不存在');
        }
        
        if (!password_verify($oldPassword, $admin['password'])) {
            $this->error('原密码错误');
        }
        
        // 更新密码
        $admin->save([
            'password' => password_hash($newPassword, PASSWORD_DEFAULT)
        ]);
        
        // 记录操作日志
        $this->logService->addLog($adminId, 'update_password', '修改密码');
        
        $this->success('修改成功');
    }

    /**
     * 修改个人信息
     */
    public function updateInfo()
    {
        $adminId = session('admin_id');
        if (!$adminId) {
            $this->error('请先登录', null, 401);
        }
        
        $nickname = input('post.nickname');
        $avatar = input('post.avatar');
        
        if (empty($nickname)) {
            $this->error('昵称不能为空');
        }
        
        $admin = AdminModel::find($adminId);
        if (!$admin) {
            $this->error('管理员不存在');
        }
        
        // 更新信息
        $admin->save([
            'nickname' => $nickname,
            'avatar' => $avatar
        ]);
        
        // 记录操作日志
        $this->logService->addLog($adminId, 'update_info', '修改个人信息');
        
        $this->success('修改成功');
    }

    /**
     * 获取操作日志列表
     */
    public function getLogList()
    {
        $adminId = session('admin_id');
        if (!$adminId) {
            $this->error('请先登录', null, 401);
        }
        
        $page = input('get.page', 1);
        $limit = input('get.limit', 10);
        
        $where = [
            'admin_id' => $adminId
        ];
        
        $list = $this->logService->getList($where, $page, $limit);
        
        $this->success('获取成功', $list);
    }

    /**
     * 清空操作日志
     */
    public function clearLog()
    {
        $adminId = session('admin_id');
        if (!$adminId) {
            $this->error('请先登录', null, 401);
        }
        
        // 清空日志
        $this->logService->clearLog($adminId);
        
        // 记录操作日志
        $this->logService->addLog($adminId, 'clear_log', '清空操作日志');
        
        $this->success('清空成功');
    }

    /**
     * 获取菜单列表
     */
    public function getMenuList()
    {
        $adminId = session('admin_id');
        if (!$adminId) {
            $this->error('请先登录', null, 401);
        }
        
        // 获取权限列表
        $authList = $this->authService->getAuthList($adminId);
        
        // 获取菜单列表
        $menuList = $this->menuService->getMenuList($authList);
        
        $this->success('获取成功', $menuList);
    }

    /**
     * 获取权限列表
     */
    public function getAuthList()
    {
        $adminId = session('admin_id');
        if (!$adminId) {
            $this->error('请先登录', null, 401);
        }
        
        // 获取权限列表
        $authList = $this->authService->getAuthList($adminId);
        
        $this->success('获取成功', $authList);
    }

    /**
     * 获取角色列表
     */
    public function getRoleList()
    {
        $adminId = session('admin_id');
        if (!$adminId) {
            $this->error('请先登录', null, 401);
        }
        
        // 获取角色列表
        $roleList = $this->roleService->getList();
        
        $this->success('获取成功', $roleList);
    }

    /**
     * 获取角色信息
     */
    public function getRoleInfo()
    {
        $adminId = session('admin_id');
        if (!$adminId) {
            $this->error('请先登录', null, 401);
        }
        
        $roleId = input('get.id');
        if (empty($roleId)) {
            $this->error('参数错误');
        }
        
        // 获取角色信息
        $roleInfo = $this->roleService->getInfo($roleId);
        
        if (!$roleInfo) {
            $this->error('角色不存在');
        }
        
        $this->success('获取成功', $roleInfo);
    }

    /**
     * 添加角色
     */
    public function addRole()
    {
        $adminId = session('admin_id');
        if (!$adminId) {
            $this->error('请先登录', null, 401);
        }
        
        $name = input('post.name');
        $description = input('post.description');
        $authList = input('post.auth_list/a');
        
        if (empty($name)) {
            $this->error('角色名称不能为空');
        }
        
        // 添加角色
        $roleId = $this->roleService->add($name, $description, $authList);
        
        if (!$roleId) {
            $this->error('添加失败');
        }
        
        // 记录操作日志
        $this->logService->addLog($adminId, 'add_role', '添加角色：' . $name);
        
        $this->success('添加成功');
    }
} 